// 游戏控制器，控制使用类

import Food from "./Food";
import ScorePanel from "./ScorePanel";
import Snake from "./Snake";

class GameControl{

  snake: Snake
  food: Food
  scorePanel: ScorePanel
  // 存储按键响应值(上下左右)
  direction: string = ''
  // 游戏是否结束
  isLive = true

  constructor(){
    this.snake = new Snake
    this.food = new Food
    this.scorePanel = new ScorePanel
    this.init()
  }

  // 游戏初始化，调用后游戏开始
  init(){
    // 绑定键盘事件
    // this.keydownHandle.bind(this)将this绑定到keydown事件，不绑定指向document
    document.addEventListener('keydown', this.keydownHandle.bind(this))
    this.run()
  }

  // 键盘按下响应函数
  keydownHandle(event: KeyboardEvent){
    // console.log(event.key)
    // console.log(this)
    // 检查按键是否合法

    this.direction = event.key
  }

  // 控制蛇移动方法
  run() {
    let X = this.snake.x
    let Y = this.snake.y

    switch (this.direction){
      case "ArrowUp":
      case "Up":
        Y -= 10
        break
      case "ArrowDown":
      case "Down":
        Y += 10
        break
      case "ArrowLeft":
      case "Left":
        X -= 10
        break
      case "ArrowRight":
      case "Right":
        X += 10
        break
    }
    // 检查蛇是否吃到食物
    this.checkEat(X, Y)
    try {
      // 修改坐标值
      this.snake.x=X
      this.snake.y=Y
    } catch (e) {
      // 撞墙，游戏结束
      alert(e+'GAME OVER!')
      this.isLive = false
    }

    // 开启定时调用
    this.isLive && setTimeout(this.run.bind(this), 300-(this.scorePanel.level-1)*30)
  }
  // 检查蛇是否吃到食物
  checkEat(x:number,y:number){
    if(x === this.food.x && y === this.food.y){
        // 重置食物位置
        this.food.change()
        // 分数增加
        this.scorePanel.addScore()
        // 蛇增加一节
        this.snake.addBody()
    }
  }
}
export default GameControl